package main.com.cyz.Queue;

import main.com.cyz.Queue.Bean.MyQueue;

import java.util.Iterator;

/**
 * @author fox
 * @version 1.0
 * @description 手写单向环形链表队列
 * @date 2024/5/19 9:01
 */
public class MyLinkedQuery<E> implements MyQueue<E>,Iterable<E> {

    private class Node<E>{
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    private Node<E> head = new Node<>(null,null);
    private Node<E> tail = head;
    private int size;
    private int capacity = Integer.MAX_VALUE;

    {
        tail.next = head;
    }

    public MyLinkedQuery() {

    }

    public MyLinkedQuery(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            Node<E> point = head.next;

            @Override
            public boolean hasNext() {
                return point != head;
            }

            @Override
            public E next() {
                E value = point.value;
                point = point.next;
                return value;
            }
        };
    }

    @Override
    public Boolean offer(E value) {
        if (isFull()){
            return false;
        }
        Node<E> newNode = new Node<>(value, head);
        tail.next = newNode;
        tail = newNode;
        size ++;
        return true;
    }

    @Override
    public E poll() {

        if (isEmpty()){
            return null;
        }

        Node<E> first = head.next;
        head.next = first.next;
        if (first == tail){
            tail = head;
        }
        size --;
        return first.value;
    }

    @Override
    public E peek() {

        if (isEmpty()){
            return null;
        }

        return head.next.value;
    }

    @Override
    public Boolean isEmpty() {
        return head == tail;
    }

    @Override
    public Boolean isFull() {
        return size == capacity;
    }
}
